https://leetcode-cn.com/problems/last-stone-weight/
/**
* 说明:
* 1、感觉有点投机取巧了,使用了Java里面的集合排序方法
* 2、考虑过写一个方法找到列表里面的第一和第二大的数字,但是好像不如直接使用Java自带的排序算法好
*
* 思路:
* 1、先把数组存入到集合里面去,集合排序和操作方便些
* 2、把集合排序
* 3、写一个fun,比较x,y,如果相等就返回 -1,不相等就返回 y-x
* 4、while循环条件集合元素个数大于1
* 5、接收fun返回的数字,如果不是-1,就把结果插入list,并且从新排序list
*
*
* @author 小道仙
* @date 2019年10月14日
*/
public int lastStoneWeight(int[] stones) {
if (stones.length == 1){
return stones[0];
}
List<Integer> list = new ArrayList<>();
for (int i = 0;i < stones.length; i++){
list.add(stones[i]);
}
Collections.sort(list);
while (list.size() > 1){
int result = fun(list.remove(list.size() - 2), list.remove(list.size() - 1));
if (result != -1){
list.add(result);
Collections.sort(list);
}
}
if (list.size() == 0){
return 0;
}else{
return list.get(0);
}
}
int fun (int x, int y){
if (x == y){
return -1;
}else{
return y-x;
}
}